package cn.spream.jstudy.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-3-26
 * Time: 上午8:34
 * To change this template use File | Settings | File Templates.
 */
public class XMLUtils {

    private static final String CHARSET = "utf-8";

    /**
     * xml解析为xml
     * 使用默认编码UTF-8
     *
     * @param xml
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Document parseXML(String xml) throws IOException, DocumentException {
        return parseXML(xml, CHARSET);
    }

    /**
     * xml解析为document
     *
     * @param xml
     * @param encoding 指定编码
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Document parseXML(String xml, String encoding) throws DocumentException, IOException {
        Document document = null;
        SAXReader reader = new SAXReader();
        reader.setEncoding(encoding);
        Reader sr = null;
        try {
            sr = new StringReader(xml);
            document = reader.read(sr);
        } finally {
            if (sr != null) {
                sr.close();
            }
        }
        return document;
    }

    /**
     * 获取单个节点的文本内容
     *
     * @param node
     * @param xpathExpression
     * @return 无此节点则返回 null
     */
    public static String getNodeText(Node node, String xpathExpression) {
        String result = null;
        Node resultNode = node.selectSingleNode(xpathExpression);
        if (resultNode != null) {
            result = resultNode.getText();
        }
        return result;
    }

    /**
     * 获取多个节点
     *
     * @param node
     * @param xpathExpression
     * @return
     */
    public static List<Node> getListNode(Node node, String xpathExpression) {
        return node.selectNodes(xpathExpression);
    }

}
